//
//  RefundDetailVC.m
//  yunbaolive
//
//  Created by ybRRR on 2020/2/20.
//  Copyright © 2020 cat. All rights reserved.
//

#import "RefundDetailVC.h"
#import "RefundHeadView.h"
#import "RefuseRefundVC.h"
#import "RefundDetailModel.h"
#import "JCHATConversationViewController.h"

@interface RefundDetailVC ()
{
    UIScrollView *backScroll;
}

@property (nonatomic, strong)RefundHeadView *headView;
@property (nonatomic, strong)UIView *historyView;
@property (nonatomic, strong)UIView *infoView;

@property (nonatomic, strong)UIImageView *orderImg;
@property (nonatomic, strong)UILabel *orderTitleLb;
@property (nonatomic, strong)UILabel *orderContentLb;
@property (nonatomic, strong)UILabel *orderPriceLb;
@property (nonatomic, strong)UILabel *orderCountLb;
@property (nonatomic, strong)RefundDetailModel *model;
@end

@implementation RefundDetailVC

#pragma mark------卖家获取退款详情----------
-(void)reqestRefundInfo{
    NSString *url = [purl stringByAppendingFormat:@"?service=Seller.getGoodsOrderRefundInfo"];
    NSDictionary *signdic = @{@"uid":[Config getOwnID],@"token":[Config getOwnToken],@"orderid":self.orderModel.idStr,@"time":[NSNumber numberWithLong: (long)[[NSDate date] timeIntervalSince1970]]};
    NSString *sign = [PublicObj sortString:signdic];

    NSDictionary *dic = @{
                          @"uid":[Config getOwnID],
                          @"token":[Config getOwnToken],
                          @"orderid":self.orderModel.idStr,
                          @"time":[NSNumber numberWithLong: (long)[[NSDate date] timeIntervalSince1970]],
                          @"sign":sign
                            };
    
    [WYNetworking postWithUrl:@"Seller.getGoodsOrderRefundInfo" Dic:dic Suc:^(int code, id info, NSString *msg) {
        if (code ==0) {
            NSDictionary *infos = [info firstObject];
            self.model = [RefundDetailModel modelWithDictionary:infos];
            
            //头部视图
            [backScroll addSubview:self.headView];
            
            [backScroll addSubview:self.historyView];
            
            [backScroll addSubview:self.infoView];
            
            backScroll.contentSize = CGSizeMake(_window_width, self.headView.height+self.historyView.height+self.infoView.height);

        }else{
            [MBProgressHUD showError:msg];
        }

        } Fail:^(id fail) {
            
     }];
}
- (UIStatusBarStyle)preferredStatusBarStyle {
    if (@available(iOS 13.0,*)) {
        return UIStatusBarStyleDarkContent;
    }
    return UIStatusBarStyleDefault;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.titleL.text = YZMsg(@"退款详情");
    self.subNavi.backgroundColor = UIColor.whiteColor;
    self.titleL.textColor = UIColor.blackColor;
    [self.leftBtn setImage:[UIImage imageNamed:@"pub_back_black"] forState:0];
    self.naviLine.hidden = NO;
    self.naviLine.backgroundColor = RGB(245, 245, 245);

    backScroll = [[UIScrollView alloc]init];
    backScroll.frame = CGRectMake(0, 64+statusbarHeight, _window_width, _window_height-64-statusbarHeight);
    backScroll.backgroundColor = UIColor.whiteColor;
    [self.view addSubview:backScroll];
    
    [self reqestRefundInfo];
    
}

-(void)agreeRefundOrder{
        NSDictionary *signdic = @{@"uid":[Config getOwnID],@"token":[Config getOwnToken],@"orderid":self.orderModel.idStr,@"time":[NSNumber numberWithLong: (long)[[NSDate date] timeIntervalSince1970]]};
        NSString *sign = [PublicObj sortString:signdic];

        NSDictionary *dic = @{
                              @"uid":[Config getOwnID],
                              @"token":[Config getOwnToken],
                              @"orderid":self.orderModel.idStr,
                              @"type":@"1",
                              @"reasonid":@"",
                              @"refuse_desc":@"",
                              @"time":[NSNumber numberWithLong: (long)[[NSDate date] timeIntervalSince1970]],
                              @"sign":sign
                                };
    
    [WYNetworking postWithUrl:@"seller.setGoodsOrderRefund" Dic:dic Suc:^(int code, id info, NSString *msg) {
        if (code ==0) {
            [MBProgressHUD showError:msg];
            [[YBBaseAppDelegate sharedAppDelegate]popViewController:YES];
        }else{
            [MBProgressHUD showError:msg];
        }

        } Fail:^(id fail) {
            
     }];
}
-(RefundHeadView *)headView{
    YBWeakSelf;
    if (!_headView) {
        _headView = [[RefundHeadView alloc]initWithFrame:CGRectMake(0, 0, _window_width, 120)];
        [_headView setRefundData:self.model];
        _headView.clickEvent = ^(NSString * _Nonnull btnTitle) {
            if ([btnTitle isEqual:YZMsg(@"同意")]) {
                [weakSelf agreeRefundOrder];
            }else if ([btnTitle isEqual:YZMsg(@"拒绝")]){
                [weakSelf refushClick];
            }
        };
    }
    return _headView;
}
-(UIView *)historyView{
    if (!_historyView) {
        _historyView = [[UIView alloc]init];
        _historyView.backgroundColor = UIColor.whiteColor;
        _historyView.frame = CGRectMake(0, _headView.bottom+5, _window_width, 50);
        [backScroll addSubview:_historyView];
        UILabel *titlelb = [[UILabel alloc]init];
        titlelb.frame  = CGRectMake(12, 50/2-10, 80+100, 20);
        titlelb.text = YZMsg(@"协商历史");
        titlelb.font = [UIFont systemFontOfSize:14];
        titlelb.textColor = [UIColor blackColor];
        [_historyView addSubview:titlelb];
        
        UIImageView *rightImg = [[UIImageView alloc]init];
        rightImg.frame =CGRectMake(_window_width-30, 50/2-8, 16, 16);
        rightImg.image = [UIImage imageNamed:@"shop_right"];
        [_historyView addSubview:rightImg];
        
        UIButton *historyBtn = [UIButton buttonWithType:0];
        historyBtn.frame = CGRectMake(0, 0, _historyView.width, _historyView.height);
        [historyBtn addTarget:self action:@selector(historyRefundClick) forControlEvents:UIControlEventTouchUpInside];
        [_historyView addSubview:historyBtn];
    }
    return _historyView;
}

-(UIView *)infoView{
    if (!_infoView) {
        _infoView = [[UIView alloc]initWithFrame:CGRectMake(0, _historyView.bottom+5, _window_width, 450)];
        _infoView.backgroundColor = UIColor.whiteColor;
        
        UILabel *lb = [[UILabel alloc]initWithFrame:CGRectMake(12, 10, 80, 20)];
        lb.text = YZMsg(@"退款信息");
        lb.font = [UIFont systemFontOfSize:14];
        lb.textColor = [UIColor blackColor];
        [_infoView addSubview:lb];
        
        _orderImg = [[UIImageView alloc]init];
        _orderImg.frame = CGRectMake(12, lb.bottom+5, 90, 90);
        _orderImg.backgroundColor = [UIColor lightGrayColor];
        _orderImg.layer.cornerRadius = 5;
        _orderImg.layer.masksToBounds = YES;
        _orderImg.contentMode = UIViewContentModeScaleAspectFill;
        [_orderImg sd_setImageWithURL:[NSURL URLWithString:self.model.spec_thumb_format]];
        [_infoView addSubview:_orderImg];
        
        _orderTitleLb = [[UILabel alloc]init];
        _orderTitleLb.textColor = [UIColor blackColor];
        _orderTitleLb.font = [UIFont systemFontOfSize:14];
        _orderTitleLb.text = self.model.goods_name;
        [_infoView addSubview:_orderTitleLb];
        [_orderTitleLb mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_orderImg.mas_right).offset(5);
            make.top.equalTo(_orderImg).offset(8);
            make.height.mas_equalTo(18);
        }];
        
        _orderPriceLb = [[UILabel alloc]init];
        _orderPriceLb.textColor = [UIColor blackColor];
        _orderPriceLb.font = [UIFont systemFontOfSize:14];
        _orderPriceLb.text =[NSString stringWithFormat:@"%@%@",YZMsg(@"¥"),self.model.price];// @"¥188.00";
        _orderPriceLb.textAlignment = NSTextAlignmentRight;
        [_infoView addSubview:_orderPriceLb];
        [_orderPriceLb mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(_infoView).offset(-10);
            make.centerY.height.equalTo(_orderTitleLb);
        }];
        _orderContentLb = [[UILabel alloc]init];
        _orderContentLb.textColor = Normal_TextColor;
        _orderContentLb.font = [UIFont systemFontOfSize:14];
        _orderContentLb.text =self.model.spec_name;// @"麻辣鲜香味";
        [_infoView addSubview:_orderContentLb];
        [_orderContentLb mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_orderTitleLb);
            make.top.equalTo(_orderTitleLb.mas_bottom).offset(5);
            make.height.equalTo(_orderTitleLb);
        }];
        
        _orderCountLb = [[UILabel alloc]init];
        _orderCountLb.textColor = Normal_TextColor;
        _orderCountLb.font = [UIFont systemFontOfSize:14];
        _orderCountLb.text =[NSString stringWithFormat:@"%@%@",YZMsg(@"x"), self.model.nums];// @"x1";
        _orderCountLb.textAlignment = NSTextAlignmentRight;
        [_infoView addSubview:_orderCountLb];
        [_orderCountLb mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(_infoView).offset(-10);
            make.centerY.height.equalTo(_orderContentLb);
        }];

        
        [PublicObj lineViewWithFrame:CGRectMake(0, _orderImg.bottom+5, _window_width, 5) andColor:RGB(245, 245, 245) andView:_infoView];
        
        NSArray *arr = @[YZMsg(@"买家昵称:"),YZMsg(@"订单状态:"),YZMsg(@"退款方式:"),YZMsg(@"退款金额:"),YZMsg(@"退款原因:"),YZMsg(@"申请时间:"),YZMsg(@"退款单号:"),YZMsg(@"问题描述:")];
        for (int i = 0;i < arr.count ; i++) {
            UILabel *lb = [[UILabel alloc]init];
            lb.font = [UIFont systemFontOfSize:14];
            lb.textColor = Normal_TextColor;
            lb.text = arr[i];
            [_infoView addSubview:lb];
            [lb mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(_infoView).offset(12);
                make.top.equalTo(_orderImg.mas_bottom).offset(15+i*30);
                make.height.mas_equalTo(20);
            }];
            
            
            UILabel *infoLb = [[UILabel alloc]init];
            infoLb.font = [UIFont systemFontOfSize:14];
            if (i > 0 && i < 4) {
                infoLb.textColor = Pink_Cor;
            }else{
                infoLb.textColor = [UIColor grayColor];
            }
            [_infoView addSubview:infoLb];
            if (i == 7) {
                [infoLb mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.left.equalTo(lb.mas_right).offset(5);
                    make.top.equalTo(lb.mas_top).offset(-2);
                    make.width.mas_equalTo(_window_width-100);
                }];

            }else{
                [infoLb mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.left.equalTo(lb.mas_right).offset(5);
                    make.top.equalTo(lb.mas_top);
                    make.width.mas_equalTo(_window_width-100);
                }];

            }
            
            switch (i) {
                case 0:
                    infoLb.text = self.model.user_nickname;
                    break;
                case 1:
                    infoLb.text = self.model.status_name;
                    break;
                case 2:{
                    //（退款类型 0 仅退款 1 退货退款）
                    NSString *typeStr;
                    if ([self.model.type isEqual:@"0"]) {
                        typeStr =YZMsg(@"仅退款");
                    }else{
                        typeStr =YZMsg(@"退货退款");

                    }
                    infoLb.text = typeStr;

                }
                    break;
                case 3:
                    infoLb.text = [NSString stringWithFormat:@"¥%@",self.model.total];
                    break;
                case 4:
                    infoLb.text = self.model.reason;
                    break;
                case 5:
                    infoLb.text = self.model.addtime;
                    break;
                case 6:
                    infoLb.text = self.model.orderno;
                    break;
                case 7:{
                    infoLb.text = self.model.refund_status_content;
                    infoLb.lineBreakMode = NSLineBreakByWordWrapping;
                    infoLb.numberOfLines = 0;
                    CGFloat textHeight = [PublicObj heightOfString:self.model.refund_status_content andFont:[UIFont systemFontOfSize:14] andWidth:_window_width-100];
                    [infoLb mas_updateConstraints:^(MASConstraintMaker *make) {
                        make.height.mas_equalTo(10+textHeight);

                    }];
                    _infoView.size = CGSizeMake(_window_width, 450+textHeight);
            }
                    break;

                default:
                    break;
            }
        }
//        [_infoView layoutIfNeeded];
        CGFloat textHeight = [PublicObj heightOfString:self.model.refund_status_content andFont:[UIFont systemFontOfSize:14] andWidth:_window_width-100];

        [PublicObj lineViewWithFrame:CGRectMake(0, (_orderImg.bottom+25)+arr.count*30+textHeight, _window_width, 1) andColor:RGB(245, 245, 245) andView:_infoView];


        UIButton *kefuBtn = [UIButton buttonWithType:0];
        [kefuBtn setBackgroundColor: UIColor.whiteColor];
        [kefuBtn setImage:[UIImage imageNamed:@"联系客服"] forState:0];
        [kefuBtn setTitle:YZMsg(@"联系买家") forState:0];
        [kefuBtn setTitleColor:[UIColor blackColor] forState:0];
        kefuBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        [kefuBtn addTarget:self action:@selector(kefuBtnClick) forControlEvents:UIControlEventTouchUpInside];
        [kefuBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 10, 0, 0 )];
        [_infoView addSubview:kefuBtn];
        [kefuBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_infoView);
            make.top.equalTo(_orderImg.mas_bottom).offset(30+arr.count*30+textHeight);
            make.width.equalTo(_infoView).multipliedBy(0.5);
            make.height.mas_equalTo(40);
        }];
        
        UIButton *callBtn = [UIButton buttonWithType:0];
        [callBtn setBackgroundColor: UIColor.whiteColor];
        [callBtn setImage:[UIImage imageNamed:@"拨打电话"] forState:0];
        [callBtn setTitle:YZMsg(@"拨打电话") forState:0];
        [callBtn setTitleColor:[UIColor blackColor] forState:0];
        callBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        [callBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 10, 0, 0 )];
        [callBtn addTarget:self action:@selector(callBtnClick) forControlEvents:UIControlEventTouchUpInside];

        [_infoView addSubview:callBtn];
        
        [callBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(kefuBtn.mas_right);
            make.top.equalTo(kefuBtn);
            make.width.equalTo(_infoView).multipliedBy(0.5);
            make.height.mas_equalTo(40);
        }];
        
        [PublicObj lineViewWithFrame:CGRectMake(_window_width/2, (_orderImg.bottom+25)+arr.count*30+textHeight, 1, 50) andColor:RGB(245, 245, 245) andView:_infoView];

    }
    return _infoView;
}
-(void)refushClick{
    UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:nil message:YZMsg(@"选择拒绝前请先尝试与买家进行充分沟通") preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *goAction = [UIAlertAction actionWithTitle:YZMsg(@"继续") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        RefuseRefundVC *refuse = [[RefuseRefundVC alloc]init];
        refuse.orderId = self.orderModel.idStr;
        [[YBBaseAppDelegate sharedAppDelegate]pushViewController:refuse animated:YES];
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:YZMsg(@"取消") style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    [alertControl addAction:goAction];
    [alertControl addAction:cancelAction];
    [goAction setValue:[UIColor grayColor] forKey:@"_titleTextColor"];
    [cancelAction setValue:Normal_Color forKey:@"_titleTextColor"];
    [self.navigationController presentViewController:alertControl animated:YES completion:nil];
}

//查看协商历史
-(void)historyRefundClick{
    NSString *url =[NSString stringWithFormat:@"%@/appapi/goodsorderrefund/index",h5url];

    PubH5 *h5VC = [[PubH5 alloc]init];
    h5VC.url = [self addurl:url addModel:self.model];;
    [[YBBaseAppDelegate sharedAppDelegate]pushViewController:h5VC animated:YES];

}
//所有h5需要拼接uid和token
-(NSString *)addurl:(NSString *)url addModel:(RefundDetailModel *)models{
    return [url stringByAppendingFormat:@"&uid=%@&token=%@&orderid=%@&user_type=seller",[Config getOwnID],[Config getOwnToken],self.orderModel.idStr];
}

//联系买家
-(void)kefuBtnClick{
    NSDictionary *userDic = @{
        @"id":self.model.refund_uid,
        @"user_nickname":self.model.user_nickname,
        @"avatar":self.model.shop_avatar,
    };
    [[YBMessageManager shareManager] chatWithUser:userDic];
}
-(void)callBtnClick{
    NSString *phone =[NSString stringWithFormat:@"tel://%@",self.model.order_phone] ;
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:phone]];

}
@end
